package com.xscha.tableforge.service.impl;

import com.xscha.tableforge.model.entity.App;
import com.xscha.tableforge.model.vo.PageReq;
import com.xscha.tableforge.model.vo.PageResult;
import com.xscha.tableforge.repository.AppRepository;
import com.xscha.tableforge.service.AppService;
import com.xscha.tableforge.service.BaseService;
import com.xscha.tableforge.utils.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 应用服务实现类
 */
@Service
public class AppServiceImpl extends BaseService<App> implements AppService {

    private final AppRepository appRepository;

    @Autowired
    public AppServiceImpl(AppRepository appRepository) {
        this.appRepository = appRepository;
    }

    @Override
    public List<App> findAllBySpaceId(String spaceId) {
        return appRepository.findAllBySpaceId(spaceId);
    }

    @Override
    public Optional<App> findById(String id) {
        return appRepository.findById(id);
    }

    @Override
    @Transactional
    public App createApp(App app, String userId) {
        app.setId(IdUtil.createAppId());
        app.setCreatedTime(LocalDateTime.now());
        app.setCreatedBy(userId);
        return appRepository.save(app);
    }

    @Override
    @Transactional
    public App updateApp(App app, String userId) {
        app.setLastModifiedTime(LocalDateTime.now());
        app.setLastModifiedBy(userId);
        return appRepository.update(app);
    }

    @Override
    @Transactional
    public void deleteApp(String id, String userId) {
        appRepository.softDelete(id, userId);
    }

    @Override
    public PageResult<App> findPageBySpaceId(String spaceId, PageReq pageRequest) {
		PageReq processedReq = processPageRequest(pageRequest);
        return appRepository.findPageBySpaceId(spaceId, processedReq);
    }

	@Override
	protected Class<App> getEntityClass() {
		return App.class;
	}
}